package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.azureBlob.AzureBlobTool;
import com.cci.kangdao.common.RedisKeys;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.UploadPicturesService;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service("UploadPicturesService")
public class UploadPicturesImpl implements UploadPicturesService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Resource
    private PropertiesUtils propertiesUtils;

    @Resource
    private WorkOrderTDao workOrderTDao;

    @Resource
    private CompanyTDao companyTDao;

    @Autowired
    private UploadPicturesDao uploadPicturesDao;

    @Resource
    private WorkOrderRemedyPictureDao workOrderRemedyPictureDao;

    @Resource
    private WorkOrderPictureCategoryTDao workOrderPictureCategoryTDao;

    @Resource
    private WorkOrderPictureDetailTDao workOrderPictureDetailTDao;

    @Resource
    private RedisClientUtils redisClientUtils;

    @Resource
    private WorkOrderPicsDao workOrderPicsDao;

    @Resource
    private DictionariesTDao dictionariesTDao;

    @Override
    public ModelAndView upload(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        // 获取登录用户信息
        UserT userT = UserThreadLocal.get();
        // 通过请求获取必要参数
        //照片描述
        String description = MapUtils.getString(map, "description");
        //照片号
        String picNo = MapUtils.getString(map, "picNo");
        // 获取工单ID
        long orderId = MapUtils.getLongValue(map, "orderId", 0);
        // 操作类型，1-图片上传，2-照片补拍，默认1
        String type = MapUtils.getString(map, "type", "1");
        // 将前端赋值放入map中
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        map.put("creator", userT.getId());
        map.put("createTime", currentTime);
        map.put("description", description);
        map.put("picNo", picNo);

        // 将照片信息上传到微软云
        String fileName = getAzureFileUrl(request, map);
        if (StringUtils.isEmpty(fileName)) {
            ParameterTool.writeResponse(response, 1, "文件上传失败，请重试！");
            return null;
        }
        map.put("pictureUrl", fileName);

        int resultCount = 0;

        // 原有上传逻辑
        if (type.equals("1")) {
            // 先存库，再通知
            //根据工单id和picNo查看图片是否存在
            int workOrderPicsCount = uploadPicturesDao.getWorkOrderPicsCountByOrderIdPicNo(orderId, picNo);
            if (workOrderPicsCount != 0) {  //存在照片，执行修改操作
                resultCount = uploadPicturesDao.updateWorkOrderPics(map);
            } else {   //不存在照片，执行新增操作
                resultCount = uploadPicturesDao.addWorkOrderPics(map);
            }
        } else {
            // 补拍逻辑
            Long remedyId = MapUtils.getLong(map,"remedyId");
            if(NumberUtils.isPositiveNum(remedyId)){
                WorkOrderRemedyPicture workOrderRemedyPicture = workOrderRemedyPictureDao.selectByPrimaryKey(remedyId);
                workOrderRemedyPicture.setPictureUrl(MapUtils.getString(map,"pictureUrl"));
                workOrderRemedyPicture.setRemedyCount(workOrderRemedyPicture.getRemedyCount() + 1);
                workOrderRemedyPicture.setLocation(MapUtils.getString(map,"location"));
                workOrderRemedyPicture.setLocLon(MapUtils.getDouble(map,"positionLon"));
                workOrderRemedyPicture.setLocLat(MapUtils.getDouble(map,"positionLat"));
                workOrderRemedyPicture.setImei(MapUtils.getString(map,"IMEI"));
                workOrderRemedyPicture.setTakeTime(currentTime);
                workOrderRemedyPicture.setUpdator(userT.getId());
                workOrderRemedyPicture.setUpdateTime(currentTime);
                resultCount = workOrderRemedyPictureDao.updateByPrimaryKeySelective(workOrderRemedyPicture);
            }
        }

        if (resultCount > 0) {
            // 保存成功，同步照片信息至CRM
            Map<String, Object> workOrderMap = workOrderTDao.getOrderById(orderId);
            long companyId = MapUtils.getLongValue(workOrderMap, "OrderChannel", 0);
            if (companyId == 1) {
                syncPictureToCCI(companyId, map, workOrderMap, type);
            }
            // 响应前端
            Map<String, Object> resultMap = new HashMap<>(2);
            resultMap.put("picNo", picNo);
            resultMap.put("pictureUrl", fileName);
            ParameterTool.writeSuccessResponse(response, resultMap);
        } else {
            // 保存失败，直接响应前端
            ParameterTool.writeResponse(response, 1, "上传失败");
        }
        return null;

    }

    private String getAzureFileUrl(HttpServletRequest request, Map<String, Object> map) {
        String basePath = request.getSession().getServletContext().getRealPath(propertiesUtils.getPropertiesValue("upload").trim());
        File fileDir = new File(basePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        map.put("basePath", basePath);
        // 本地文件位置
        String fileName = Upload_Util.uploadData(map);
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        // 将服务器照片上传至微软云
        String filePath = basePath + File.separator + fileName;
        fileName = AzureBlobTool.uploadBlob(propertiesUtils.getPropertiesValue("accountName").trim(),
                propertiesUtils.getPropertiesValue("blobConnection").trim(),
                propertiesUtils.getPropertiesValue("containerName").trim(),
                filePath);
        if (StringUtils.isNotEmpty(fileName)) {
            try {
                // 删除服务器文件
                FileUtils.forceDelete(new File(filePath));
            } catch (IOException e) {
                log.warn("删除服务器照片失败" + e.getMessage(), e);
            }
            return fileName;
        }
        return null;
    }

    private String getAzureFileUrl(HttpServletRequest request, Map<String, Object> map,String fileRealPath) {
        String basePath = request.getSession().getServletContext().getRealPath(propertiesUtils.getPropertiesValue("upload").trim());
        File fileDir = new File(basePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        map.put("basePath", basePath);
        // 本地文件位置
        String fileName = Upload_Util.uploadDataNoTime(map);
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        // 将服务器照片上传至微软云
        String filePath = basePath + File.separator + fileName;
        fileName = AzureBlobTool.uploadBlob(propertiesUtils.getPropertiesValue("accountName").trim(),
                propertiesUtils.getPropertiesValue("blobConnection").trim(),
                propertiesUtils.getPropertiesValue("containerName").trim(),
                filePath,fileRealPath);
        if (StringUtils.isNotEmpty(fileName)) {
            try {
                // 删除服务器文件
                FileUtils.forceDelete(new File(filePath));
            } catch (IOException e) {
                log.warn("删除服务器照片失败" + e.getMessage(), e);
            }
            return fileName;
        }
        return null;
    }

    private void syncPictureToCCI(Long companyId, Map<String, Object> map, Map<String, Object> workOrderMap, String type) {
        Map<String, Object> crmMap = new HashMap<>();
        crmMap.put("orderNo", workOrderMap.get("OrderNo"));
        crmMap.put("CRMNo", workOrderMap.get("OrderNoCrm"));

        double positionLon = MapUtils.getDoubleValue(map, "positionLon", 0.0);
        double positionLat = MapUtils.getDoubleValue(map, "positionLat", 0.0);
        int picLocation = MapUtils.getIntValue(map, "picNo", 0);
        Map<String, Object> picMap = new HashMap<>();
        picMap.put("description", MapUtils.getString(map, "description"));
        picMap.put("picLocation", picLocation);
        picMap.put("picUrl", MapUtils.getString(map, "pictureUrl"));
        picMap.put("shootingTime", map.get("createTime"));
        picMap.put("shootingLocation", map.get("location"));
        picMap.put("shootingLat", positionLat);
        picMap.put("shootingLon", positionLon);
        picMap.put("shootingType", type);

        List<Map<String, Object>> picList = new ArrayList<>();
        picList.add(picMap);
        crmMap.put("pictures", picList);
        CompanyT companyT = companyTDao.getCompanyInfoByCompanyID(companyId);
        CRMApiUtils.getCRMServiceApi().syncWorkOrderPics(companyT.getCompanyNo(), crmMap, null);
        //添加照片同步信息
        WorkOrderPicsSynchroT synchroT = new WorkOrderPicsSynchroT();
        synchroT.setOrderId(MapUtils.getLongValue(map, "orderId"));
        synchroT.setPicNo(MapUtils.getString(map, "picNo"));
        synchroT.setSynchroJson(JsonUtils.toJsonString(crmMap));
        synchroT.setCreator(companyId);
        synchroT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        uploadPicturesDao.addWorkOrderPicsSynchro(synchroT);
    }

    @Override
    public ModelAndView getPicturesList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        // 获取必要参数
        String orderId = MapUtils.getString(map, "orderId", "");
        if (StringUtils.isEmpty(orderId)) {
            ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
        }
        // 查询订单照片列表
        List<Map<String, Object>> picList = uploadPicturesDao.getPicturesList(map);
        Map<String, Object> data = new HashMap<>(1);
        if (CollectionUtils.isNotEmpty(picList)) {
            data.put("pictureList", picList);
            List<WorkOrderRemedyPicture> remedyPictureList = workOrderRemedyPictureDao.selectListByOrderId(Long.valueOf(orderId));
            List<Map<String,Object>> remedyResultList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(remedyPictureList)){
                for(WorkOrderRemedyPicture workOrderRemedyPicture:remedyPictureList){
                    if(StringUtils.isEmpty(workOrderRemedyPicture.getPictureUrl())){
                        continue;
                    }
                    Map<String,Object> resultMap = new HashMap<>(3);
                    resultMap.put("remedyId",String.valueOf(workOrderRemedyPicture.getId()));
                    resultMap.put("pictureUrl",workOrderRemedyPicture.getPictureUrl());
                    resultMap.put("description",workOrderRemedyPicture.getDescription());
                    resultMap.put("comments",workOrderRemedyPicture.getComments());
                    resultMap.put("picNo",workOrderRemedyPicture.getPictureLocation());
                    remedyResultList.add(resultMap);
                }
            }
            data.put("remedyPictureList", remedyResultList);
        } else {
            data.put("pictureList", new ArrayList<>(0));
        }
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    @Override
    public void getRemedyPictureList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        // 获取必要参数
        Long orderId = MapUtils.getLong(map, "orderId",0L);
        List<WorkOrderRemedyPicture> remedyPictureList = workOrderRemedyPictureDao.selectListByOrderId(orderId);
        List<Map<String,Object>> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(remedyPictureList)){
            for(WorkOrderRemedyPicture workOrderRemedyPicture:remedyPictureList){
                Map<String,Object> resultMap = new HashMap<>(3);
                resultMap.put("remedyId",String.valueOf(workOrderRemedyPicture.getId()));
                resultMap.put("orderId",workOrderRemedyPicture.getOrderId());
                resultMap.put("pictureUrl",StringUtils.isEmpty(workOrderRemedyPicture.getPictureUrl())?"":workOrderRemedyPicture.getPictureUrl());
                resultMap.put("description",workOrderRemedyPicture.getDescription());
                resultMap.put("comments",workOrderRemedyPicture.getComments());
                resultMap.put("picNo",workOrderRemedyPicture.getPictureLocation());
                resultList.add(resultMap);
            }
        }
        Map<String,Object> result = new HashMap<>(1);
        result.put("remedyPictureList",resultList);
        ParameterTool.writeSuccessResponse(response,result);
    }

    @Override
    public void getManagementPictureList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        // 获取必要参数
        Long orderId = MapUtils.getLong(map, "orderId", 0L);
        if (!NumberUtils.isPositiveNum(orderId)) {
            ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
            return;
        }
        // 获取工单信息
        WorkOrderT workOrderT = workOrderTDao.getWorkOrderTByOrderId(orderId);
        if(null == workOrderT){
            ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
            return;
        }

        Map<String, Object> data = new HashMap<>(1);

        // 查询订单照片列表
        List<Map<String, Object>> picList = uploadPicturesDao.getPicturesList(map);
        Map<String,Object> dataPictureMap = new LinkedHashMap<>();
        if (CollectionUtils.isNotEmpty(picList)) {
            for(Map<String, Object> dataMap: picList){
                String picNo = MapUtils.getString(dataMap,"picNo");
                if(StringUtils.isNotEmpty(picNo)){
                    dataPictureMap.put(picNo,dataMap);
                }
            }

            List<WorkOrderRemedyPicture> remedyPictureList = workOrderRemedyPictureDao.selectListByOrderId(orderId);
            List<Map<String,Object>> remedyResultList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(remedyPictureList)){
                for(WorkOrderRemedyPicture workOrderRemedyPicture:remedyPictureList){
                    if(StringUtils.isEmpty(workOrderRemedyPicture.getPictureUrl())){
                        continue;
                    }
                    Map<String,Object> resultMap = new HashMap<>(3);
                    resultMap.put("remedyId",String.valueOf(workOrderRemedyPicture.getId()));
                    resultMap.put("pictureUrl",workOrderRemedyPicture.getPictureUrl());
                    resultMap.put("description",workOrderRemedyPicture.getDescription());
                    resultMap.put("comments",workOrderRemedyPicture.getComments());
                    resultMap.put("picNo",workOrderRemedyPicture.getPictureLocation());
                    remedyResultList.add(resultMap);
                }
            }
            data.put("remedyPictureList", remedyResultList);
        }else{
            data.put("remedyPictureList", new ArrayList<>(0));
        }

        // 获取工单管理类型
        List<Map<String,Object>> categoryList = new ArrayList<>();
        Integer category = MapUtils.getInteger(map,"category",0);
        //获取  上线时间     字典表
        String splitPhotosBefore = dictionariesTDao.getListByDTableName("SplitPhotosBeforeTime");
        //获取 category =0  对应的值
        String SplitPhotosBeforeValues = dictionariesTDao.getListByDTableName("SplitPhotosBeforeValues");
        Integer  categoryNum = -1;
        if (StringUtils.isNotBlank(SplitPhotosBeforeValues)) {
            categoryNum = Integer.valueOf(SplitPhotosBeforeValues);
        }
        if(category==0
                &&StringUtils.isNotBlank(splitPhotosBefore)
                &&StringUtils.isNotBlank(SplitPhotosBeforeValues)
                &&StringUtils.isNotBlank(workOrderT.getCreateTime())
                &&(!LocalTimeUtil.isBefore(workOrderT.getCreateTime(),splitPhotosBefore))){
            category = Integer.valueOf(SplitPhotosBeforeValues);
        }

        List<WorkOrderPictureCategoryT> categoryTList = workOrderPictureCategoryTDao.selectListByChannelId(Long.valueOf(workOrderT.getOrderChannel()),category);

        if(CollectionUtils.isNotEmpty(categoryTList)){
            Long id = categoryTList.get(0).getId();
            for(WorkOrderPictureCategoryT categoryT : categoryTList){
                Map<String,Object> pictureCategoryMap = new HashMap<>();
                pictureCategoryMap.put("categoryId",categoryT.getId());
                pictureCategoryMap.put("title",categoryT.getTitle());
                pictureCategoryMap.put("orderStatus",categoryT.getOrderStatus());
                List<Map<String,Object>> pictureMapList = new ArrayList<>();
                List<WorkOrderPictureDetailT> workOrderPictureDetailTList = workOrderPictureDetailTDao.selectListByCategoryId(categoryT.getId());
                if(CollectionUtils.isNotEmpty(workOrderPictureDetailTList)){
                    for(WorkOrderPictureDetailT detailT:workOrderPictureDetailTList){
                        Map<String,Object> mergeMap = new HashMap<>();
                        mergeMap.put("requiredShooting",detailT.getRequiredShooting());
//                        mergeMap.put("isRequired",detailT.getIsRequired());
                        if (workOrderT.getOrderChannel()==1 && categoryNum==category && detailT.getCategoryId()==id) {
                            if("Truck 卡车".equals( workOrderT.getMarketType())|| "Bus 客车".equals( workOrderT.getMarketType())){
                                if ("1007".equals(detailT.getPictureNo())) {
                                    mergeMap.put("isRequired", 1);
                                }else {
                                    mergeMap.put("isRequired", detailT.getIsRequired());
                                }
                            }else {
                                if ("1002".equals(detailT.getPictureNo())) {
                                    mergeMap.put("isRequired", 1);
                                }else {
                                    mergeMap.put("isRequired", detailT.getIsRequired());
                                }
                            }
                        }else {
                            mergeMap.put("isRequired", detailT.getIsRequired());
                        }
                        mergeMap.put("position",detailT.getPosition());
                        mergeMap.put("isSupplement",detailT.getIsSupplement());
                        mergeMap.put("samplePicture",detailT.getSamplePicture());
                        mergeMap.put("sampleThumbnailPicture",detailT.getSampleThumbnailPicture());
                        mergeMap.put("version",detailT.getVersion());
                        mergeMap.put("typeStr",detailT.getTypeStr());
                        mergeMap.put("limitationNum",this.isWhite(workOrderT.getOrderChannel(), workOrderT.getServiceStationId())?detailT.getLimitationNum():0);
                        if(!NumberUtils.isPositiveNum(detailT.getIsSupplement())){
                            // 普通业务照片
                            mergeMap.put("picNo",detailT.getPictureNo());
                            mergeMap.put("title",detailT.getPictureTitle());
                            mergeMap.put("description",detailT.getPictureDesc());
                            Map<String,Object> dataPic = (Map<String, Object>) MapUtils.getObject(dataPictureMap,detailT.getPictureNo());
                            if(MapUtils.isNotEmpty(dataPic)){
                                String url = MapUtils.getString(dataPic,"picUrl");
                                mergeMap.put("pictureUrl",url);
                            }else{
                                mergeMap.put("pictureUrl","");
                            }
                            pictureMapList.add(mergeMap);
                        }else{
                            // 其他图片
                            String prefix = detailT.getPictureNo();
                            List<String> otherPictureNo = new ArrayList<>();
                            for(String key:dataPictureMap.keySet()){
                                if(key.startsWith(prefix)){
                                    otherPictureNo.add(key);
                                }
                            }
                            if(CollectionUtils.isNotEmpty(otherPictureNo)){
                                // 存在其他照片
                                for(String key:otherPictureNo){
                                    Map<String,Object> dataOtherPictureMap = (Map<String, Object>) MapUtils.getObject(dataPictureMap,key);
                                    Map<String,Object> otherPictureMap = (Map<String, Object>) BeanUtils.deepClone(mergeMap);
                                    String url = MapUtils.getString(dataOtherPictureMap,"picUrl");
                                    String pictureNo = MapUtils.getString(dataOtherPictureMap,"picNo");
                                    String description = MapUtils.getString(dataOtherPictureMap,"description");
                                    otherPictureMap.put("pictureUrl",url);
                                    otherPictureMap.put("picNo",pictureNo);
                                    otherPictureMap.put("title",description);
                                    otherPictureMap.put("description",description);
                                    pictureMapList.add(otherPictureMap);
                                }
                            }else{
                                // 不存在其他照片
                                continue;
                            }
                        }

                    }
                }
                pictureCategoryMap.put("orderPicture",pictureMapList);
                categoryList.add(pictureCategoryMap);
            }
            data.put("pictureList", categoryList);
        } else {
            data.put("pictureList", new ArrayList<>(0));
        }
        ParameterTool.writeSuccessResponse(response, data);
    }

    public boolean isWhite(int orderChannel,long serviceStationId){
        //获取使用的渠道
        String OcrChannel = dictionariesTDao.getListByDTableName("OcrChannel");
        if (StringUtils.isNotBlank(OcrChannel)) {
            List<Integer> ocrChannelList = JSON.parseArray(OcrChannel, Integer.class);
            if (ocrChannelList != null && ocrChannelList.size() > 0) {
                boolean anyMatch = ocrChannelList.stream().anyMatch(e -> e.intValue() == orderChannel);
                if(anyMatch){
                    String ocrStation = dictionariesTDao.getListByDTableName("OcrStation");
                    if (StringUtils.isNotBlank(ocrStation)) {
                        List<Long> ocrStationList = JSON.parseArray(ocrStation, Long.class);
                        if (ocrChannelList != null && ocrChannelList.size() > 0) {
                            anyMatch = ocrStationList.stream().anyMatch(e -> e.longValue() == serviceStationId);
                        }
                    }
                }
                return anyMatch;
            }
        }
        return false;
    }


    @Override
    public void newUpload(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        // 获取登录用户信息
        UserT userT = UserThreadLocal.get();
        // 通过请求获取必要参数
        //照片描述
        String description = MapUtils.getString(map, "description");
        //照片号
        String picNo = MapUtils.getString(map, "picNo");
        // 获取工单ID
        long orderId = MapUtils.getLongValue(map, "orderId", 0);
        // 操作类型，1-图片上传，2-照片补拍，默认1
        String type = MapUtils.getString(map, "type", "1");
        // 将前端赋值放入map中
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        map.put("creator", userT.getId());
        map.put("createTime", currentTime);
        map.put("description", description);
        Integer isSupplement = MapUtils.getInteger(map,"isSupplement");
        if(StringUtils.isEmpty(picNo) && NumberUtils.isPositiveNum(isSupplement)){
            Long categoryId = MapUtils.getLong(map,"categoryId");
            picNo = getPicNo(orderId,categoryId);
        }
        // 处理picNo和故障信息关系
        picNo = getNewPictureNum(picNo, map);
        // 将照片信息上传到微软云
        String fileName = getAzureFileUrl(request, map);
        if (StringUtils.isEmpty(fileName)) {
            ParameterTool.writeResponse(response, 1, "文件上传失败，请重试！");
            return ;
        }
        map.put("pictureUrl", fileName);

        int resultCount = 0;

        // 原有上传逻辑
        if (type.equals("1")) {
            // 先存库，再通知
            //根据工单id和picNo查看图片是否存在
            int workOrderPicsCount = uploadPicturesDao.getWorkOrderPicsCountByOrderIdPicNo(orderId, picNo);
            if (workOrderPicsCount != 0) {  //存在照片，执行修改操作
                resultCount = uploadPicturesDao.updateWorkOrderPics(map);
            } else {   //不存在照片，执行新增操作
                resultCount = uploadPicturesDao.addWorkOrderPics(map);
            }
        } else {
            // 补拍逻辑
            Long remedyId = MapUtils.getLong(map,"remedyId");
            if(NumberUtils.isPositiveNum(remedyId)){
                WorkOrderRemedyPicture workOrderRemedyPicture = workOrderRemedyPictureDao.selectByPrimaryKey(remedyId);
                workOrderRemedyPicture.setPictureUrl(MapUtils.getString(map,"pictureUrl"));
                workOrderRemedyPicture.setRemedyCount(workOrderRemedyPicture.getRemedyCount() + 1);
                workOrderRemedyPicture.setLocation(MapUtils.getString(map,"location"));
                workOrderRemedyPicture.setLocLon(MapUtils.getDouble(map,"positionLon"));
                workOrderRemedyPicture.setLocLat(MapUtils.getDouble(map,"positionLat"));
                workOrderRemedyPicture.setImei(MapUtils.getString(map,"IMEI"));
                workOrderRemedyPicture.setTakeTime(currentTime);
                workOrderRemedyPicture.setUpdator(userT.getId());
                workOrderRemedyPicture.setUpdateTime(currentTime);
                resultCount = workOrderRemedyPictureDao.updateByPrimaryKeySelective(workOrderRemedyPicture);
            }
        }

        if (resultCount > 0) {
            // 保存成功，同步照片信息至CRM
            Map<String, Object> workOrderMap = workOrderTDao.getOrderById(orderId);
            long companyId = MapUtils.getLongValue(workOrderMap, "OrderChannel", 0);
            if (companyId == 1) {
                syncPictureToCCI(companyId, map, workOrderMap, type);
            }
            // 响应前端
            Map<String, Object> resultMap = new HashMap<>(2);
            resultMap.put("picNo", picNo);
            resultMap.put("pictureUrl", fileName);
            ParameterTool.writeSuccessResponse(response, resultMap);
        } else {
            // 保存失败，直接响应前端
            ParameterTool.writeResponse(response, 1, "上传失败");
        }
    }

    @Override
    public void ocrUploadPictures(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String folder = MapUtils.getString(map, "folder","");
        String fileName = getAzureFileUrl(request, map,folder+"/"+LocalTimeUtil.getFormatterRealCurrentTime(LocalTimeUtil.DTF_DAY_FORMATTER)+"/");
        ParameterTool.writeSuccessResponse(response,fileName);
    }

     /**
      * @description: 维修中-某个故障信息的唯一识别码和照片绑定关系
      * @param:
      * @return:
      * @exception:
      * @author: shiliqiang
      * @company: CTY Technology Co.,Ltd
      * @since: 2021/7/22 9:08
      * @version: V1.0
      */
    private String getNewPictureNum (String picNo, Map map) {
        // 维修中-某个故障信息的唯一识别码
        String faultId = MapUtils.getString(map, "faultId");
        if (StringUtils.isNotEmpty(faultId)) {
            picNo = picNo+"-"+faultId;
            map.put("picNo", picNo);
        } else {
            map.put("picNo", picNo);
        }
        return picNo;
    }

    @Override
    @Transactional
    public void deletePicture(Map<String, Object> map) {
        // 获取登录用户信息
        UserT userT = UserThreadLocal.get();
        String picNo = MapUtils.getString(map, "picNo");
        // 获取工单ID
        long orderId = MapUtils.getLongValue(map, "orderId", 0);
        if(StringUtils.isNotEmpty(picNo) && NumberUtils.isPositiveNum(orderId)){
            workOrderPicsDao.disablePicture(orderId,picNo,userT.getId(), LocalTimeUtil.getRealCurrentTime());
            ParameterTool.writeSuccessResponse(RequestContextHolder.getResponse());
        }else{
            ParameterTool.writeResponse(RequestContextHolder.getResponse(), SMSEnum.type17.getIndex(), SMSEnum.type17.getName());
        }
    }

    private String getPicNo(Long orderId,Long categoryId){
        Long nextNo = redisClientUtils.incr(RedisKeys.pictureNoKey(orderId,categoryId),24*60*60*7);
        WorkOrderPictureDetailT detailT = workOrderPictureDetailTDao.selectSupplementByCategoryId(categoryId);
        return String.format("%s%03d",detailT.getPictureNo(),nextNo);
    }

    //同步自行诊断工单照片集合
    public void syncPictureListToCCI(Long companyId, List<PictureManagementT> picList, Map<String, Object> workOrderMap, String type) {
        Map<String, Object> crmMap = new HashMap<>();
        crmMap.put("orderNo", workOrderMap.get("OrderNo"));
        crmMap.put("CRMNo", workOrderMap.get("OrderNoCrm"));
        List<Map<String, Object>> addPicList = new ArrayList<>();
        for (PictureManagementT pictureManagementT : picList) {
            double positionLon = pictureManagementT.getLocLon();
            double positionLat = pictureManagementT.getLocLat();
            //int picLocation = MapUtils.getIntValue(map, "picNo", 0);
            Map<String, Object> picMap = new HashMap<>();
            picMap.put("description",pictureManagementT.getPicDescription());
            //picMap.put("picLocation", picLocation);
            picMap.put("picUrl",pictureManagementT.getPictureUrl());
            picMap.put("shootingTime",pictureManagementT.getCreateTime());
            picMap.put("shootingLocation",pictureManagementT.getLocation());
            picMap.put("shootingLat", positionLat);
            picMap.put("shootingLon", positionLon);
            picMap.put("shootingType", type);

            addPicList.add(picMap);
        }

        crmMap.put("pictures", addPicList);
        CompanyT companyT = companyTDao.getCompanyInfoByCompanyID(companyId);
        CRMApiUtils.getCRMServiceApi().syncWorkOrderPics(companyT.getCompanyNo(), crmMap, null);
    }
}
